Imports System.IO
Imports System.Xml
Imports System
Public Class frmMain

#Region "Toolbar/Menu"

#Region "Search"

    Private Sub txtSearch_TextChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles txtSearch.TextChanged
        Dim AllBookmarks As TreeNodeCollection = trvBookmarks.Nodes
        Dim Bookmark As TreeNode
        For Each Bookmark In AllBookmarks
            ExitSearch(Bookmark)
            FindBookmark(Bookmark, txtSearch.TextLength)
        Next
        btnExitSearch.Visible = True
    End Sub

    Sub FindBookmark(ByVal SearchResult As TreeNode, ByVal Length As Integer)
        Dim NewResult As TreeNode
        For Each NewResult In SearchResult.Nodes
            If txtSearch.TextLength = Length Then
                If NewResult.Name.EndsWith("url") = True Then
                    If NewResult.Text.ToLower.Contains(txtSearch.Text) = False Then
                        NewResult.ForeColor = Color.Transparent
                    End If
                Else : NewResult.Parent.Expand()
                    NewResult.EnsureVisible()
                End If
            Else : Exit Sub
            End If
            FindBookmark(NewResult, Length)
        Next
    End Sub

    Private Sub btnExitSearch_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnExitSearch.Click
        txtSearch.Text = String.Empty
        Dim AllBookmarks As TreeNodeCollection = trvBookmarks.Nodes
        Dim Bookmark As TreeNode
        For Each Bookmark In AllBookmarks
            ExitSearch(Bookmark)
            btnExitSearch.Visible = False
        Next
    End Sub

    Sub ExitSearch(ByVal Node As TreeNode)
        Dim NewNode As TreeNode
        For Each NewNode In Node.Nodes
            NewNode.ForeColor = Color.Black
            ExitSearch(NewNode)
        Next
    End Sub
#End Region

    Private Sub BookmarkToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles NewToolStripButton.Click, BookmarkToolStripMenuItem.Click, BookmarkToolStripMenuItem1.Click, BookmarkToolStripMenuItem.Click, BookmarkToolStripMenuItem2.Click
        fsWatcher.EnableRaisingEvents = False
        Dim NewBookmarkDialog As New frmNewBookmark
        NewBookmarkDialog.ShowDialog()
        fsWatcher.EnableRaisingEvents = True
    End Sub

    Private Sub FolderToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles FolderToolStripMenuItem.Click, FolderToolStripMenuItem1.Click, FolderToolStripMenuItem2.Click
        fsWatcher.EnableRaisingEvents = False
        Dim FolderName As String = InputBox("Name the new folder", "New Folder", "New Folder")
        Dim NewFolderNode As New TreeNode
        NewFolderNode.ImageIndex = 1
        NewFolderNode.SelectedImageIndex = 1
        NewFolderNode.Text = FolderName
        If FolderName <> "" Then
            If trvBookmarks.SelectedNode IsNot Nothing Then
                Directory.CreateDirectory(trvBookmarks.SelectedNode.Name & "\" & FolderName)
                NewFolderNode.Name = trvBookmarks.SelectedNode.Name & "\" & FolderName
                trvBookmarks.SelectedNode.Nodes.Add(NewFolderNode)
            Else : Directory.CreateDirectory(FavoritesFolder & FolderName)
                NewFolderNode.Name = FavoritesFolder & FolderName & "\"
                trvBookmarks.TopNode.Nodes.Add(NewFolderNode)
            End If
        End If
        fsWatcher.EnableRaisingEvents = True
    End Sub

    Private Sub FindToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles FindToolStripMenuItem.Click
        txtSearch.Focus()
    End Sub

    Private Sub DeleteToolStripButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles DeleteToolStripButton.Click, DeleteToolStripMenuItem.Click, DeleteToolStripMenuItem1.Click
        DeleteBookmark(trvBookmarks.SelectedNode)
    End Sub

    Private Sub RenameToolStripButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles RenameToolStripButton.Click, RenameToolStripMenuItem.Click, RenameToolStripMenuItem1.Click
        fsWatcher.EnableRaisingEvents = False
        Try
            trvBookmarks.SelectedNode.BeginEdit()
        Catch When Err.Number = 91
            ShowError("Make sure you have selected a bookmark or folder.", Err.ToString, Err.Number)
        Catch ex As Exception
            ShowError(ex.Message, ex.ToString, Err.Number)
        End Try
        fsWatcher.EnableRaisingEvents = True
    End Sub

    Private Sub MoveToolStripButton_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MoveToolStripButton.Click, MoveToolStripMenuItem.Click, MoveToolStripMenuItem1.Click
        fsWatcher.EnableRaisingEvents = False
        If trvBookmarks.SelectedNode IsNot Nothing Then
            frmMoveBookmark.ShowDialog()
        End If
        fsWatcher.EnableRaisingEvents = True
    End Sub

    Private Sub AboutToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles AboutToolStripMenuItem.Click
        frmAbout.ShowDialog()
    End Sub

    Private Sub OptionsToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles OptionsToolStripMenuItem.Click
        frmOptions.ShowDialog()
    End Sub

    Private Sub RecentToolStripMenuItem_DropDownItemClicked(ByVal sender As Object, ByVal e As System.Windows.Forms.ToolStripItemClickedEventArgs) Handles RecentToolStripMenuItem.DropDownItemClicked
        System.Diagnostics.Process.Start(AccessBookmarks.ReadBookmark(e.ClickedItem.Name))
    End Sub

    Private Sub DocumentationToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles DocumentationToolStripMenuItem.Click
        Try
            Dim HelpFile As String = My.Application.Info.DirectoryPath & "\Documentation.chm"
            System.Diagnostics.Process.Start(HelpFile)
        Catch When Err.Number = 5
            ShowError(My.Application.Info.ProductName & " cannot find the help file.", Err.ToString, Err.Number)
        Catch ex As Exception
            ShowError(ex.Message, ex.ToString, Err.Number)
        End Try
    End Sub

    Private Sub CheckForUpdatesToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CheckForUpdatesToolStripMenuItem.Click
        CheckForUpdates("http://update.openbyte.info/OpenBookmarks.ini", False)
    End Sub

    Private Sub WebsiteToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles WebsiteToolStripMenuItem.Click
        System.Diagnostics.Process.Start("http://www.openbyte.info/")
    End Sub

    Private Sub CheckFoDuplicatesToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles FindDuplicateBookmarksToolStripMenuItem.Click
        FindingDuplicates = True
        Dim FindDupes As New frmSearchDuplicates
        FindDupes.ShowDialog()
        FindDupes.Dispose()
    End Sub

    Private Sub FindDeadBookmarksToolStripMenuItem_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles FindDeadBookmarksToolStripMenuItem.Click
        FindingDuplicates = False
        Dim FindDeadLinks As New frmSearchDuplicates
        FindDeadLinks.Text = "Find Dead Bookmarks"
        FindDeadLinks.ShowDialog()
        FindDeadLinks.Dispose()
    End Sub

    Private Sub ReportBugToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ReportBugToolStripMenuItem.Click
        System.Diagnostics.Process.Start("http://www.codeplex.com/openbookmarks/WorkItem/Create.aspx")
    End Sub
#End Region

#Region "Bookmark Treeview Events"

#Region "Drag and dropping nodes"
    'TODO: Stop program from freezing if a node is drag&dropped onto itself.
    Private Sub trvBookmarks_DragDrop(ByVal sender As Object, ByVal e As System.Windows.Forms.DragEventArgs) Handles trvBookmarks.DragDrop
        fsWatcher.EnableRaisingEvents = False
        If e.Data.GetDataPresent("System.Windows.Forms.TreeNode", True) = False Then Exit Sub
        Dim Display As TreeView = CType(sender, TreeView)
        Dim Bookmark As TreeNode = CType(e.Data.GetData("System.Windows.Forms.TreeNode"), TreeNode)
        Dim TargetFolder As TreeNode = Display.SelectedNode
        If TargetFolder Is Nothing Then
            Bookmark.Remove()
            Display.TopNode.Nodes.Add(Bookmark)
            If Bookmark.Name.EndsWith("url") Then
                AccessBookmarks.MoveBookmark(Bookmark.Name, Display.TopNode.Name & "\" & Bookmark.Text & ".url")
            Else : AccessBookmarks.MoveFolder(Bookmark.Name, Display.TopNode.Name)
            End If
        ElseIf TargetFolder.Name.EndsWith("url") = False Then
            Bookmark.Remove()
            TargetFolder.Nodes.Add(Bookmark)
            If Bookmark.Name.EndsWith("url") Then
                AccessBookmarks.MoveBookmark(Bookmark.Name, Display.SelectedNode.Name & "\" & Bookmark.Text & ".url")
            Else : AccessBookmarks.MoveFolder(Bookmark.Name, Display.SelectedNode.Name)
            End If
        ElseIf TargetFolder Is trvBookmarks.TopNode Or TargetFolder Is Bookmark Then
            'Do nothing
        End If
        Bookmark.EnsureVisible()
        Display.SelectedNode = Bookmark
        trvBookmarks.Sort()
        fsWatcher.EnableRaisingEvents = True
    End Sub

    Private Sub trvBookmarks_DragEnter(ByVal sender As Object, ByVal e As System.Windows.Forms.DragEventArgs) Handles trvBookmarks.DragEnter
        If e.Data.GetDataPresent("System.Windows.Forms.TreeNode", True) Then
            e.Effect = DragDropEffects.Move
        Else : e.Effect = DragDropEffects.None
        End If
    End Sub

    Private Sub trvBookmarks_DragOver(ByVal sender As Object, ByVal e As System.Windows.Forms.DragEventArgs) Handles trvBookmarks.DragOver
        If e.Data.GetDataPresent("System.Windows.Forms.TreeNode", True) = False Then Exit Sub
        Dim Display As TreeView = CType(sender, TreeView)
        Dim pt As Point = CType(sender, TreeView).PointToClient(New Point(e.X, e.Y))
        Dim TargetFolder As TreeNode = Display.GetNodeAt(pt)
        If Not (Display.SelectedNode Is TargetFolder) Then
            Display.SelectedNode = TargetFolder
            Dim dropNode As TreeNode = CType(e.Data.GetData("System.Windows.Forms.TreeNode"), TreeNode)
            Do Until TargetFolder Is Nothing
                If TargetFolder Is dropNode Then
                    e.Effect = DragDropEffects.None
                    Exit Sub
                End If
                TargetFolder = TargetFolder.Parent
            Loop
        End If
        e.Effect = DragDropEffects.Move
    End Sub

    Private Sub trvBookmarks_ItemDrag(ByVal sender As Object, ByVal e As System.Windows.Forms.ItemDragEventArgs) Handles trvBookmarks.ItemDrag
        DoDragDrop(e.Item, DragDropEffects.Move)
    End Sub
#End Region

    Private Sub trvBookmarks_AfterLabelEdit(ByVal sender As Object, ByVal e As System.Windows.Forms.NodeLabelEditEventArgs) Handles trvBookmarks.AfterLabelEdit
        fsWatcher.EnableRaisingEvents = False
        If CheckIfBookmark(e.Node.Name) = True Then
            AccessBookmarks.RenameBookmark(trvBookmarks.SelectedNode.Name, e.Label)
            trvBookmarks.SelectedNode.Name = e.Node.Parent.Name & "\" & e.Label & ".url"
        Else : AccessBookmarks.RenameFolder(trvBookmarks.SelectedNode.Name, e.Label)
            trvBookmarks.SelectedNode.Name = e.Node.Parent.Name & "\" & e.Label
        End If
        fsWatcher.EnableRaisingEvents = True
    End Sub



    Private Sub trvBookmarks_AfterSelect(ByVal sender As Object, ByVal e As System.Windows.Forms.TreeViewEventArgs) Handles trvBookmarks.AfterSelect
        Try
            If My.Settings.PrefetchBookmarks = True Then
                frmPreview.webPreview.Navigate(AccessBookmarks.ReadBookmark(trvBookmarks.SelectedNode.Name))
            End If
            lblStatus.Text = AccessBookmarks.ReadBookmark(trvBookmarks.SelectedNode.Name)
            'tlsBtnStatus.Text = trvBookmarks.SelectedNode.Name 'Used for debugging purposes.
        Catch ex As Exception
            'Do Nothing
        End Try
    End Sub

    Private Sub trvBookmarks_NodeMouseClick(ByVal sender As Object, ByVal e As System.Windows.Forms.TreeNodeMouseClickEventArgs) Handles trvBookmarks.NodeMouseClick
        If e.Button = Windows.Forms.MouseButtons.Right Then
            trvBookmarks.SelectedNode = e.Node
        End If
    End Sub

    Private Sub trvBookmarks_NodeMouseDoubleClick(ByVal sender As Object, ByVal e As System.Windows.Forms.TreeNodeMouseClickEventArgs) Handles trvBookmarks.NodeMouseDoubleClick
        Try
            If My.Settings.EnableDoubleClick = True And e.Node.Name.EndsWith("url") Then
                If My.Settings.LaunchOnDoubleClick = True Then
                    System.Diagnostics.Process.Start(AccessBookmarks.ReadBookmark(trvBookmarks.SelectedNode.Name))
                    SaveRecentSite(trvBookmarks.SelectedNode.Name)
                    AddToRecentMenu(RecentToolStripMenuItem)
                Else : frmPreview.Show() : frmPreview.webPreview.Navigate(AccessBookmarks.ReadBookmark(trvBookmarks.SelectedNode.Name))
                End If

            End If
        Catch When Err.Number = 76
            'Do nothing.
        Catch When Err.Number = 13
            'Do nothing. This stops the program from crashing when the user tries to open a folder in the web browser.
        Catch ex As Exception
            ErrorMessage = ex.ToString()
            ShowError(ex.Message, Err.Description, Err.Number)
        End Try
    End Sub

    Private Sub trvBookmarks_KeyUp(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles trvBookmarks.KeyUp
        If e.KeyCode = Keys.Delete And trvBookmarks.SelectedNode IsNot Nothing Then
            DeleteBookmark(trvBookmarks.SelectedNode)
        ElseIf e.KeyCode = Keys.F2 Then
            trvBookmarks.SelectedNode.BeginEdit()
        End If
    End Sub

    Private Sub trvBookmarks_AfterExpand(ByVal sender As Object, ByVal e As System.Windows.Forms.TreeViewEventArgs) Handles trvBookmarks.AfterExpand
        e.Node.Tag = True
        SaveExpandedState()
    End Sub
    Private Sub trvBookmarks_AfterCollapse(ByVal sender As Object, ByVal e As System.Windows.Forms.TreeViewEventArgs) Handles trvBookmarks.AfterCollapse
        e.Node.Tag = False
        SaveExpandedState()
    End Sub
#End Region

#Region "Form Events"
    Private Sub frmMain_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
        If My.Settings.EnableTray = True And My.Settings.CloseToTray = True Then
            e.Cancel = True
            Me.Hide()
            icoTray.Visible = True
        Else : icoTray.Visible = False
            My.Settings.Save()
            End
        End If
    End Sub

    Private Sub frmMain_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        LoadBookmarks(trvBookmarks)
    End Sub

    Private Sub frmMain_Resize(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Resize
        If My.Settings.EnableTray = True And My.Settings.MinToTray = True And Me.WindowState = FormWindowState.Minimized Then
            Me.Hide()
            icoTray.Visible = True
        End If
    End Sub
#End Region

#Region "Status Bar"
    Private Sub lblStatus_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles lblStatus.Click
        My.Computer.Clipboard.SetText(lblStatus.Text)
    End Sub
#End Region

#Region "System Tray"
    Private Sub icoTray_DoubleClick(ByVal sender As Object, ByVal e As System.EventArgs) Handles icoTray.DoubleClick
        Me.Show()
        Me.WindowState = FormWindowState.Normal
    End Sub

    Private Sub cmnuTrayIcon_VisibleChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles cmnuTrayIcon.VisibleChanged
        Try
            Dim xmlDoc As New XmlDocument()
            Dim tsMenu As ToolStripMenuItem
            Dim RootMenu As New ToolStripMenuItem
            RootMenu.Text = "Bookmarks"
            RootMenu.Name = FavoritesFolder
            xmlDoc.Load("Bookmarks.xml")
            BookmarksToolStripMenuItem.DropDownItems.Clear()
            tsMenu = New ToolStripMenuItem
            tsMenu = BookmarksToolStripMenuItem
            AddMenu(xmlDoc.DocumentElement, tsMenu)
            trvBookmarks.TopNode.Expand()
        Catch xmlEx As XmlException
            MessageBox.Show(xmlEx.Message)
        Catch ex As Exception
            MessageBox.Show(ex.Message)
        End Try
    End Sub

    Private Sub AddMenu(ByVal inXmlNode As XmlNode, ByVal inToolStripMenu As ToolStripMenuItem)
        Dim xNode As XmlNode
        Dim tsMenu As ToolStripMenuItem
        Dim nodeList As XmlNodeList
        Dim i As Integer
        If inXmlNode.HasChildNodes Then
            nodeList = inXmlNode.ChildNodes
            i = 0
            While i <= nodeList.Count - 1
                xNode = inXmlNode.ChildNodes(i)
                Dim NewBookmark As New ToolStripMenuItem
                If xNode.Name = "folder" Then
                    NewBookmark.ImageIndex = 1
                    NewBookmark.Name = xNode.Attributes(1).Value
                Else : NewBookmark.Name = xNode.Attributes(1).Value & "\" & xNode.Attributes(0).Value
                End If
                NewBookmark.Text = xNode.Attributes(0).Value
                inToolStripMenu.DropDownItems.Add(NewBookmark)
                tsMenu = inToolStripMenu.DropDownItems(i)
                i += 1
                AddMenu(xNode, tsMenu)
            End While
        Else
            Dim BookmarkText As String = inXmlNode.Attributes(0).Value
            If BookmarkText.EndsWith("url") Then 'This makes sure that any empty folders won't get their names changed
                BookmarkText = BookmarkText.Remove(BookmarkText.Length - 4, 4)
            End If
            inToolStripMenu.Text = BookmarkText
        End If
    End Sub

    Private Sub BookmarksToolStripMenuItem_DropDownItemClicked(ByVal sender As Object, ByVal e As System.Windows.Forms.ToolStripItemClickedEventArgs) Handles BookmarksToolStripMenuItem.DropDownItemClicked
        System.Diagnostics.Process.Start(AccessBookmarks.ReadBookmark(e.ClickedItem.Name))
    End Sub

    Private Sub ExitToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ExitToolStripMenuItem.Click, ExitToolStripMenuItem1.Click
        End
    End Sub
#End Region

#Region "Filesystem Watcher"
    Private Sub fsWatcher_Changed(ByVal sender As Object, ByVal e As System.IO.FileSystemEventArgs) Handles fsWatcher.Changed, fsWatcher.Created, fsWatcher.Deleted
        AccessBookmarks.GetDirectoryStructure(FavoritesFolder)
        LoadBookmarks(trvBookmarks)
    End Sub

    Private Sub fsWatcher_Renamed(ByVal sender As Object, ByVal e As System.IO.RenamedEventArgs) Handles fsWatcher.Renamed
        AccessBookmarks.GetDirectoryStructure(FavoritesFolder)
        LoadBookmarks(trvBookmarks)
    End Sub
#End Region
    Sub DeleteBookmark(ByVal SelectedBookmark As TreeNode)
        fsWatcher.EnableRaisingEvents = False
        Try
            If My.Settings.WarnOnDelete = False Then
                If SelectedBookmark.Name.EndsWith(".url") = True Then
                    AccessBookmarks.DeleteBookmark(SelectedBookmark.Name)
                Else : AccessBookmarks.DeleteFolder(SelectedBookmark.Name)
                End If
                SelectedBookmark.Remove()
            Else : If MessageBox.Show("Are you sure you want to delete this item? This action cannot be undone.", "Are you sure?", MessageBoxButtons.YesNo, MessageBoxIcon.Question) = Windows.Forms.DialogResult.Yes Then
                    If SelectedBookmark.Name.EndsWith(".url") = True Then
                        AccessBookmarks.DeleteBookmark(SelectedBookmark.Name)
                    Else : AccessBookmarks.DeleteFolder(SelectedBookmark.Name)
                    End If
                    SelectedBookmark.Remove()
                End If
            End If
        Catch When Err.Number = 5
            'Do Nothing
        Catch When Err.Number = 91
            ShowError("Make sure you have selected a folder or boomkark to delete.", Err.ToString, Err.Number)
        Catch ex As Exception
            ShowError(ex.Message, ex.ToString, Err.Number)
        End Try
        fsWatcher.EnableRaisingEvents = True
    End Sub

    Private Sub btnPreview_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnPreview.Click
        Try
            frmPreview.webPreview.Navigate(AccessBookmarks.ReadBookmark(trvBookmarks.SelectedNode.Name))
            frmPreview.ShowDialog()
            SaveRecentSite(trvBookmarks.SelectedNode.Name)
            AddToRecentMenu(RecentToolStripMenuItem)
        Catch When Err.Number = 13
            'Do nothing. This stops the program from crashing when the user tries to preview a folder.
        Catch ex As Exception
            ShowError(ex.Message, ex.ToString, Err.Number)
        End Try
    End Sub

    Private Sub btnVisit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnVisit.Click
        Try
            System.Diagnostics.Process.Start(AccessBookmarks.ReadBookmark(trvBookmarks.SelectedNode.Name))
            SaveRecentSite(trvBookmarks.SelectedNode.Name)
            AddToRecentMenu(RecentToolStripMenuItem)
        Catch When Err.Number = 13
            'Do nothing. This stops the program from crashing when the user tries to open a folder in the web browser.
        Catch ex As Exception
            If MessageBox.Show("An error has occured opening the bookmark. Would you like to save a log of the error on your desktop?", "Error Code: " & Err.Number.ToString(), MessageBoxButtons.YesNo, MessageBoxIcon.Error) = Windows.Forms.DialogResult.Yes Then
                LogError(ex.ToString)
            Else 'Do nothing
            End If
        End Try

    End Sub


End Class